package com.estar.assistsurvy.fragment;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.estar.assistsurvy.R;
import com.estar.assistsurvy.activity.CetificationActivity;
import com.estar.assistsurvy.activity.HistoryActivity;
import com.estar.assistsurvy.activity.MessagesActivity;
import com.estar.assistsurvy.activity.RoborderActivity;
import com.estar.assistsurvy.activity.ShareActivity;
import com.estar.assistsurvy.activity.TaskSuperviseActivity;
import com.estar.assistsurvy.activity.app.AssistSurvyApp;
import com.estar.assistsurvy.adapter.FragmentAdapter;
import com.estar.assistsurvy.adapter.HomePageGridviewAdapter;
import com.estar.assistsurvy.entity.Item;
import com.estar.assistsurvy.widget.NotScrollGridView;
import com.m7.imkfsdk.chat.ChatActivity;
import com.m7.imkfsdk.chat.LoadingFragmentDialog;
import com.m7.imkfsdk.chat.PeerDialog;
import com.moor.imkf.GetPeersListener;
import com.moor.imkf.IMChatManager;
import com.moor.imkf.InitListener;
import com.moor.imkf.model.entity.Peer;
import com.moor.imkf.utils.NetUtils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class HomePageFragments extends BaseFragment implements OnPageChangeListener,OnItemClickListener{

	private ViewPager homePage_vp;
	private LinearLayout pointContainer;
	private NotScrollGridView homePage_gv;
	private ArrayList<Integer> images;
	private ArrayList<ImageView> imageviews;
	private FragmentAdapter adapter;
	private int currentItem=0;
	private Timer timer;
	private Handler handler=new Handler(){
		public void handleMessage(android.os.Message msg) {
			homePage_vp.setCurrentItem(currentItem);
		};
	};
	private HomePageGridviewAdapter gvAdapter;
	private String[] titles=new String[]{"抢单","任务监管","历史任务","查勘人认证","平台信使","在线客服","邀请分享"};
	private int[] icons=new int[]{R.drawable.icon_home_01,R.drawable.icon_home_02,R.drawable.icon_home_03,
			R.drawable.icon_home_04,R.drawable.icon_home_05,R.drawable.icon_home_07,R.drawable.icon_home_08};
	private Intent intent;
	private String roleCode,authenState,dataSources,phoneNumber;
	private SharedPreferences prefer;
	private LoadingFragmentDialog loadingDialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if(view==null){
			view=inflater.inflate(R.layout.fragment_homepage,null);

		}
		initView();
		return view;	
	}

	private void initView(){
		homePage_vp=find(R.id.homePage_vp);
		pointContainer=find(R.id.pointContainer);
		homePage_gv=find(R.id.homePage_gv);
		getImages();
		adapter=new FragmentAdapter(images, getActivity());
		homePage_vp.setAdapter(adapter);
		homePage_vp.addOnPageChangeListener(this);
		gvAdapter=new HomePageGridviewAdapter(getItems(), getActivity());
		homePage_gv.setAdapter(gvAdapter);
		homePage_gv.setOnItemClickListener(this);
		prefer=getActivity().getSharedPreferences("user", Context.MODE_PRIVATE);
		authenState=prefer.getString("authenticationState", "");
		dataSources=prefer.getString("dataSources", "");
		phoneNumber=prefer.getString("phoneNumber", "");
		loadingDialog = new LoadingFragmentDialog();
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if(null==timer){
			timer=new Timer();
			timer.schedule(new MyTimerTask(), 0, 2000);
		}
		getNotReadNum();
	}

	private SharedPreferences share;
	private void getNotReadNum(){
		share=getActivity().getSharedPreferences(phoneNumber, Context.MODE_PRIVATE);
		int i=share.getInt("number", 0);
		Log.i("nf", "首页推送消息数目---->"+i);
		gvAdapter.setGvItem(i);
		gvAdapter.notifyDataSetChanged();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if(null!=timer){
			timer.cancel();
			timer=null;
		}
	}
	
	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		super.onDestroyView();
		pointContainer.removeAllViewsInLayout();
	}

	private class MyTimerTask extends TimerTask{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			currentItem++;
			if (currentItem > images.size() - 1) {
				currentItem = 0;
			}
			handler.sendEmptyMessage(1);
		}

	}

	private void getImages(){
		images=new ArrayList<Integer>();
		imageviews=new ArrayList<ImageView>();
		for(int i=0;i<1;i++){
			images.add(R.drawable.homepage);
			ImageView imageview=new ImageView(getActivity());
			imageviews.add(imageview);
			pointContainer.addView(imageview, i);
		}
	}

	private ArrayList<Item> getItems(){
		ArrayList<Item> items=new ArrayList<Item>();
		for(int i=0;i<titles.length;i++){
			Item item=new Item();
			item.setImg(icons[i]);
			item.setText(titles[i]);
			items.add(item);
		}
		return items;
	}

	private void clearState(){
		for(int i=0;i<images.size();i++){
			ImageView imageview=imageviews.get(i);
			imageview.setImageResource(R.drawable.image_indicator);
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int position) {
		// TODO Auto-generated method stub
		clearState();
		imageviews.get(position).setImageResource(R.drawable.image_indicator_focus);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		switch (position) {
		case 0:
			if(authenState.equals("0")){
				if(dataSources.equals("0")){
					setDialog();
				}else if(dataSources.equals("1")){
					showShortToast("您还未认证，请联系后台管理员进行认证操作!");
				}

			}else if(authenState.equals("1")){
				prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
				roleCode=prefer.getString("rolecode", "");
				if(roleCode.equals("6")){
					showShortToast("您无此权限进入该功能!");
				}else{
					intent=new Intent(getActivity(), RoborderActivity.class);
					startActivity(intent);
				}
			}

			break;

		case 1:
			if(authenState.equals("0")){
				if(dataSources.equals("0")){
					setDialog();
				}else if(dataSources.equals("1")){
					showShortToast("您还未认证，请联系后台管理员进行认证操作!");
				}
			}else if(authenState.equals("1")){
				prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
				roleCode=prefer.getString("rolecode", "");
				if(roleCode.equals("6")){
					intent=new Intent(getActivity(), TaskSuperviseActivity.class);
					startActivity(intent);
				}else{
					showShortToast("您无此权限进入该功能!");
				}
			}

			break;

		case 2:
			//			showShortToast("后台维护中，稍后开启");

			if(authenState.equals("0")){
				if(dataSources.equals("0")){
					setDialog();
				}else if(dataSources.equals("1")){
					showShortToast("您还未认证，请联系后台管理员进行认证操作!");
				}
			}else if(authenState.equals("1")){

				prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
				roleCode=prefer.getString("rolecode", "");
				if(roleCode.equals("6")){
					showShortToast("您无此权限进入该功能!");
				}else{
					intent=new Intent(getActivity(), HistoryActivity.class);
					startActivity(intent);
				}
			}

			break;

		case 3:
			if(authenState.equals("1")){
				prefer=getActivity().getSharedPreferences("role", Context.MODE_PRIVATE);
				roleCode=prefer.getString("rolecode", "");
				if(roleCode.equals("6")){
					showShortToast("您无此权限进入该功能!");
				}else{
					intent=new Intent(getActivity(), CetificationActivity.class);
					startActivity(intent);
				}
			}else if(authenState.equals("0")){
				if(dataSources.equals("0")){
					setDialog();
				}else if(dataSources.equals("1")){
					showShortToast("您还未认证，请联系后台管理员进行认证操作!");
				}
			}


			break;

		case 4:
			if(authenState.equals("0")){
				if(dataSources.equals("0")){
					setDialog();
				}else if(dataSources.equals("1")){
					showShortToast("您还未认证，请联系后台管理员进行认证操作!");
				}
			}else if(authenState.equals("1")){
				share.edit().clear().commit();
				intent=new Intent(getActivity(), MessagesActivity.class);
				startActivity(intent);
			}

			break;

		case 5:
//			showShortToast("客服功能正在开发中…");
			//判断版本若为6.0申请权限
            if(Build.VERSION.SDK_INT < 23) {
                init();
            }else {
                //6.0
                if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
                    //该权限已经有了
                    init();
                }else {
                    //申请该权限
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_PHONE_STATE}, 0x1111);
                }
            }
			break;

		case 6:
			intent=new Intent(getActivity(), ShareActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	private void init() {
        if(!NetUtils.hasDataConnection(getActivity())) {
            Toast.makeText(getActivity(), "当前没有网络连接", Toast.LENGTH_SHORT).show();
            return;
        }
        loadingDialog.show(getActivity().getFragmentManager(), "");
        if (AssistSurvyApp.isKFSDK) {
            loadingDialog.dismiss();
            getPeers();
        } else {
            startKFService();
        }
    }
	
	private void getPeers() {
        IMChatManager.getInstance().getPeers(new GetPeersListener() {
            @Override
            public void onSuccess(List<Peer> peers) {
                if (peers.size() > 1) {
                    PeerDialog dialog = new PeerDialog();
                    Bundle b = new Bundle();
                    b.putSerializable("Peers", (Serializable) peers);
                    b.putString("type", "init");
                    dialog.setArguments(b);
                    dialog.show(getActivity().getFragmentManager(), "");

                } else if (peers.size() == 1) {
                    startChatActivity(peers.get(0).getId());
                } else {
                    startChatActivity("");
                }
            }

            @Override
            public void onFailed() {

            }
        });
    }
	
	private void startKFService() {

        new Thread() {
            @Override
            public void run() {
                IMChatManager.getInstance().setOnInitListener(new InitListener() {
                    @Override
                    public void oninitSuccess() {
                    	AssistSurvyApp.isKFSDK = true;
                        loadingDialog.dismiss();
                        getPeers();
                        Log.d("MobileApplication", "sdk初始化成功");

                    }

                    @Override
                    public void onInitFailed() {
                    	AssistSurvyApp.isKFSDK = false;
                        loadingDialog.dismiss();
                        Toast.makeText(getActivity(), "客服初始化失败,请填写正确的accessid", Toast.LENGTH_SHORT).show();
                        Log.d("MobileApplication", "sdk初始化失败,请填写正确的accessid");
                    }
                });

                //初始化IMSdk,先填入相关参数
                String accessid="af147870-fd55-11e5-981b-5966a108e974";
                String username="人人勘-"+phoneNumber;
                String userid=phoneNumber;
                IMChatManager.getInstance().init(AssistSurvyApp.getInstance(), "action", accessid, username, userid);

            }
        }.start();

    }

    private void startChatActivity(String peerId) {
        Intent chatIntent = new Intent(getActivity(), ChatActivity.class);
        chatIntent.putExtra("PeerId", peerId);
        startActivity(chatIntent);
    }

	@SuppressLint("Override")
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		switch (requestCode) {
		case 0x1111:
			if (grantResults.length > 0
					&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
				init();
			} else {

			}
			break;
		}
	}

	private void setDialog(){
		new AlertDialog.Builder(getActivity(), AlertDialog.THEME_HOLO_LIGHT)
		.setMessage("您还未认证，是否前往认证？")
		.setPositiveButton("是", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				intent=new Intent(getActivity(), CetificationActivity.class);
				startActivity(intent);
			}
		})
		.setNegativeButton("否", new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub

			}
		})
		.create()
		.show();
	}
}
